//
//  ScanViewController.m
//  bleDemo
//
//  Created by wurz on 15/4/12.
//  Copyright (c) 2015年 wurz. All rights reserved.
//

#import "ScanViewController.h"
#import "MBProgressHUD+Show.h"
#import "HJBleInfoViewController.h"
#import "HJBleScanData.h"

@interface ScanViewController ()
{
    UITableView *_devicesTable;
    UIActivityIndicatorView *_scanIndicatorView; //扫描的菊花
    
    NSMutableArray *_hjBleArray;
    BluetoothLe *_ble;
    
    MBProgressHUD *_hud;
}

@property(nonatomic,strong)HJBleScanData *selectedScanData;

@end

@implementation ScanViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    self.extendedLayoutIncludesOpaqueBars = NO;
    self.modalPresentationCapturesStatusBarAppearance = NO;
    
    self.view.backgroundColor = [UIColor colorWithRed:239.0/255 green:236.0/255 blue:237.0/255 alpha:1];
    
    _scanIndicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    
    _devicesTable = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStyleGrouped];
    
    _devicesTable.backgroundColor = [UIColor clearColor];
    
    _devicesTable.delegate = self;
    _devicesTable.dataSource = self;
    
    [self.view addSubview:_devicesTable];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(refresh)];
    
    _hjBleArray = [[NSMutableArray alloc] init];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    _ble = [BluetoothLe shareBandConnectionWithDelegate:self];
    _ble.delegate = self;
    _hjBleArray = [NSMutableArray array];
    [_devicesTable reloadData];
    
    if (_ble.loaclState == BleLocalStatePowerOn) {
        [self refresh];
    }
    else{
        [_scanIndicatorView stopAnimating];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -- 刷新列表 
-(void)refresh
{
    _hjBleArray = [NSMutableArray array];
    [_devicesTable reloadData];
    switch (_ble.loaclState) {
        case BleLocalStatePowerOff:
            [MBProgressHUD showSuccess:@"本地蓝牙已关闭" toView:self.view duration:1.0];
            [_scanIndicatorView stopAnimating];
            break;
        case BleLocalStatePowerOn:
            [_ble startScan];
            [_scanIndicatorView startAnimating];
            break;
            
        default:
            [MBProgressHUD showSuccess:@"本地设备不支持蓝牙4.0" toView:self.view duration:1.0];
            [_scanIndicatorView stopAnimating];
            break;
    }
}

#pragma mark -- 停止扫描
-(void)stopScan
{
    [_ble stopScan];
    [_scanIndicatorView stopAnimating];
}

#pragma mark -- UITableViewDelegete
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] init];
    view.frame = CGRectMake(0, 0, tableView.frame.size.width, 30);
    //view.backgroundColor = [UIColor clearColor];
    
    UILabel *label = [[UILabel alloc] init];
    label.frame = CGRectMake(10, 0, 70, 30);
    label.text = @"蓝牙列表";
    
    _scanIndicatorView.frame = CGRectMake(label.frame.size.width+10, 0, 40, 30);
    
    [view addSubview:label];
    [view addSubview:_scanIndicatorView];
    //[_scanIndicatorView startAnimating];
    
    return view;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [_devicesTable deselectRowAtIndexPath:indexPath animated:YES];
    
    //放在连接之前会连接失败，why？
//    [self stopScan];
    
    _selectedScanData = _hjBleArray[indexPath.row];
    _hud = [MBProgressHUD showLoading:@"正在连接中。。。" toView:self.view];
    
    //连接成功，取消超时
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(connectTimeOut:) object:nil];
    [self performSelector:@selector(connectTimeOut:) withObject:_selectedScanData afterDelay:5];
    
    [_ble connect:_selectedScanData.peripheral];
    
}

#pragma mark -- UITableViewDataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _hjBleArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentify = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentify];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIdentify];
    }
    
    HJBleScanData *scanData = _hjBleArray[indexPath.row];
    cell.textLabel.text = scanData.peripheral.name;
    cell.detailTextLabel.text = [NSString stringWithFormat:@"RSSI:%@dB",scanData.RSSI];
    return cell;
}

#pragma mark -- 连接超时
//连接超时
-(void)connectTimeOut:(HJBleScanData *)hjBle
{
    [_ble disconnect:hjBle.peripheral];
    if (_hud) {
        [_hud hide:YES];
        [_hud removeFromSuperview];
        _hud = nil;
    }
    [MBProgressHUD showError:@"连接超时" toView:self.view duration:1.0];
}

#pragma mark -- BluetoothLeDegelete
-(void)ble:(BluetoothLe *)ble didLocalState:(BleLocalState)state
{
    if (state == BleLocalStatePowerOn) {
        [self refresh]; //刷新扫描列表
    }
    else{
        [self stopScan];
    }
}

-(void)ble:(BluetoothLe *)ble didScan:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData rssi:(NSNumber *)rssi
{
    //没有名字的不显示
    if (peripheral.name == nil || [peripheral.name isEqualToString:@""]){
        return ;
    }
    
    BOOL isAdd = YES;
    for (int i=0; i<_hjBleArray.count; i++) {
        HJBleScanData *temp = _hjBleArray[i];
        
        //uuid相同，则更新
        if ([temp.peripheral.identifier.UUIDString isEqualToString:peripheral.identifier.UUIDString]) {
            
            isAdd = NO;
//          temp.peripheral = peripheral;
            temp.advertisementData = advertisementData;
            if (rssi.intValue < 0) {
                temp.RSSI = rssi;
            }
            
        }
    }
    
    
    //添加数据
    if (isAdd) {
        
        HJBleScanData *scanData = [[HJBleScanData alloc] init];
        
        scanData.peripheral = peripheral;
        scanData.advertisementData = advertisementData;
        if (rssi.intValue > 0) {
            rssi = [NSNumber numberWithInt:-70];
        }
        scanData.RSSI = rssi;
        
        [_hjBleArray addObject:scanData];
    }
    
    [_devicesTable reloadData];
}

-(void) ble:(BluetoothLe *)ble didConnect:(CBPeripheral *)peripheral result:(BOOL)isSuccess{
    //取消超时
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(connectTimeOut:) object:_selectedScanData];
    
    if (_hud) {
        [_hud hide:YES];
        [_hud removeFromSuperview];
        _hud = nil;
    }
    
    if (!isSuccess) {
        [MBProgressHUD showError:@"连接失败" toView:self.view duration:1.0];
    }
    else{
        HJBleInfoViewController *hjBleView = [[HJBleInfoViewController alloc] init];
        hjBleView.scanData = _selectedScanData;
        hjBleView.hidesBottomBarWhenPushed = YES;
        hjBleView.delegate = self;
        [self.navigationController pushViewController:hjBleView animated:YES];
    }
}

-(void)ble:(BluetoothLe *)ble didDisconnect:(CBPeripheral *)peripheral
{
    
}

#pragma mark -- HJBleInfoViewControllerDelegate
-(void)hjBleViewShowMessage:(NSString *)message
{
    [MBProgressHUD showError:message toView:self.view duration:1.0];
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
